package com.litblue.artwork.task;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.litblue.artwork.mapper.LitArtworkUserMapper;
import com.litblue.starter.cache.redis.RedisCache;
import com.litblue.starter.cache.redis.RedisKeys;
import com.litblue.starter.pojo.artwork.domain.LitArtworkUser;
import com.litblue.starter.pojo.artwork.dto.LitArtworkUserDto;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.Future;

@Component
@AllArgsConstructor
@Slf4j
public class AsyncTask {

    private final RedisCache redisCache;

    private final LitArtworkUserMapper litArtworkUserMapper;

    @SneakyThrows
    @Async
     public Future<Integer> jobGetLikeCountTask(Long artworkId,String type){
        String keyFix = type.equals("0") ? "LIKE_PREFIX" : "FAVORITE_PREFIX";
        RedisKeys redisKeys = RedisKeys.forArtworkTotal(artworkId, keyFix);
        Set keys = redisCache.redisTemplate.keys("*" + redisKeys.LIT_ARTWORK_TOTAL_KEY);
        if (CollectionUtil.isNotEmpty(keys)){
            return new AsyncResult<>(keys.size());
        }else {
            LambdaQueryWrapper<LitArtworkUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LitArtworkUser::getArtworkId,artworkId)
                    .eq(LitArtworkUser::getOperateType,type);
            Integer count = litArtworkUserMapper.selectCount(queryWrapper);
            return new AsyncResult<>(count);
        }
    }
    @SneakyThrows
    @Async
    public Future<Boolean> jobGetIsLike(Long userId,Long artworkId,String type){
        String keyFix = type.equals("0") ? "LIKE_PREFIX" : "FAVORITE_PREFIX";
        LitArtworkUserDto litArtworkUserDto = new LitArtworkUserDto();
         litArtworkUserDto.setUserId(userId);
         litArtworkUserDto.setArtworkId(artworkId);
        RedisKeys redisKeys = RedisKeys.forArtworkUser(litArtworkUserDto, keyFix);
        LitArtworkUserDto litArtworkUser = redisCache.getCacheObject(redisKeys.LIT_ARTWORK_USER_KEY);
        if (ObjectUtil.isEmpty(litArtworkUser)){
            LambdaQueryWrapper<LitArtworkUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LitArtworkUser::getArtworkId,artworkId)
                    .eq(LitArtworkUser::getUserId,userId)
                    .eq(LitArtworkUser::getOperateType,keyFix);
            Integer count = litArtworkUserMapper.selectCount(queryWrapper);
            if (count==1){
                return new  AsyncResult<>(true);
            }else {
                return new  AsyncResult<>(false);
            }
        }
        return new AsyncResult<>(true);
    }
}
